package com.ruoyi.base.service.impl;

import com.ruoyi.base.domain.BaseRegion;
import com.ruoyi.base.domain.BaseRegionExcel;
import com.ruoyi.base.domain.RegionData;
import com.ruoyi.base.mapper.BaseRegionMapper;
import com.ruoyi.base.service.BaseRegionService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.excel.ClassExcelVerifyHandler;
import com.ruoyi.common.utils.excel.ExcelUtiles;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BaseRegionServiceImpl implements BaseRegionService {
    @Autowired
    private BaseRegionMapper baseRegionMapper;
    @Autowired
    private ClassExcelVerifyHandler verifyHandler;
    /**
     * 查询行政区划
     *
     * @param Code 行政区划主键
     * @return 行政区划
     */
    @Override
    public BaseRegion selectPubCodeRegionByCode(String Code)
    {
        return baseRegionMapper.selectPubCodeRegionByCode(Code);
    }

    /**
     * 查询行政区划列表
     *
     * @param pubCodeRegion 行政区划
     * @return 行政区划
     */
    @Override
    public List<BaseRegion> selectPubCodeRegionList(BaseRegion pubCodeRegion)
    {
        return baseRegionMapper.selectPubCodeRegionList(pubCodeRegion);
    }

    @Override
    public List<RegionData> selectRegionList(BaseRegion pubCodeRegion)
    {
        List<RegionData> dataList=new ArrayList<>();
        List<BaseRegion> list =baseRegionMapper.selectPubCodeRegionList(pubCodeRegion);
        for(BaseRegion pubCodeRegion1:list){
            RegionData data =new RegionData();
            data.setLabel(pubCodeRegion1.getName());
            data.setValue(pubCodeRegion1.getCode());
            data.setParentId(pubCodeRegion1.getParentCode());
            data.setOrderNum(pubCodeRegion1.getOrdernum());
            data.setChildren(getChildrenList(pubCodeRegion1.getCode()));
            dataList.add(data);
        }
//        listResult.addAll(dataList);
        return dataList;
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<BaseRegion> selectRegionListNew(BaseRegion pubCodeRegion)
    {
        List<BaseRegion> listResult=new ArrayList<>();
        if(StringUtils.isNotEmpty(pubCodeRegion.getCode())){
            pubCodeRegion.setCodes(Arrays.asList(pubCodeRegion.getCode().split(",")));
        }

        List<BaseRegion> list =baseRegionMapper.selectPubCodeRegionList(pubCodeRegion);
        for(BaseRegion pubCodeRegion1:list){
            pubCodeRegion1.setChildren(getChildrenListNew(pubCodeRegion1.getCode()));
        }
        //查当前父节点信息
        if(StringUtils.isNotEmpty(pubCodeRegion.getCurrentNode()) &&
                pubCodeRegion.getCurrentNode().equals("1")){
            BaseRegion pubCodeRegion1 =selectPubCodeRegionByCode(pubCodeRegion.getParentCode());
            listResult.add(pubCodeRegion1);
        }
        listResult.addAll(list);
        return listResult;
    }
    @Override
    public List<BaseRegion> getRegionList(BaseRegion pubCodeRegion)
    {
        List<BaseRegion> listResult=new ArrayList<>();
        if(StringUtils.isNotEmpty(pubCodeRegion.getCode())){
            pubCodeRegion.setCodes(Arrays.asList(pubCodeRegion.getCode().split(",")));
        }

        List<BaseRegion> list =baseRegionMapper.selectPubCodeRegionList(pubCodeRegion);
        for(BaseRegion pubCodeRegion1:list){
            listResult.add(pubCodeRegion1);
            List<BaseRegion> regionListNew = getRegionListNew(pubCodeRegion1.getCode());
            if(regionListNew!=null&&regionListNew.size()>0){
                listResult.addAll(regionListNew);
            }

        }
        if(StringUtils.isNotEmpty(pubCodeRegion.getCurrentNode()) &&
                pubCodeRegion.getCurrentNode().equals("1")){
            BaseRegion pubCodeRegion1 =selectPubCodeRegionByCode(pubCodeRegion.getParentCode());
            listResult.add(pubCodeRegion1);
        }
        return listResult;
    }
    /**
     * @Description //TODO 导入基础数据
     * @Date 13:07 2025/1/20
     * @Param [file, sheetName]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @Override
    public Map<String, Object> importpucodeExcel(MultipartFile file, String sheetName) {
        Map<String,Object> maplist=new HashMap<>();
        ExcelUtiles excel = new ExcelUtiles();//excel文件工具类
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String extension = "." + FilenameUtils.getExtension(fileName);
        //生成新的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
        // 根据日期生成目录
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        String dateDirPath = localPath;
        File dateDir = new File(dateDirPath);
        if (!dateDir.exists())
            dateDir.mkdirs();
        File dir = new File(dateDirPath);
        // 处理文件上传
        try {
            file.transferTo(new File(dir, newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = dir + "/" + newFileName;
        Integer sheetNumdata = 1;
        //获取对应shell页 1.根据文件获取对应shell页在根据传入的shell页名称获取对应位置
        List<Map<String, Object>> excelFileShellmaps = excel.excelFileShellurl(s);
        if (excelFileShellmaps != null && excelFileShellmaps.size() > 0) {
            for (Map excelFileShellmapss : excelFileShellmaps) {
                Object sheetName1 = excelFileShellmapss.get("sheetName");//shell名称
                Object sheetNum = excelFileShellmapss.get("sheetNum");//shell位置
                if (sheetName1.equals(sheetName)) {
                    sheetNumdata = Integer.valueOf(String.valueOf(sheetNum));
                    sheetNumdata = sheetNumdata + 1;
                }
            }
        }
        List<BaseRegionExcel> Excellist = ExcelUtiles.importExcel(s, 1, 0, 1, BaseRegionExcel.class, verifyHandler);
        String segmentTypeall = null;
        int segment=0;//如果为1代表存在为空的名称
        int codes=0;//如果为1代表存在为空的区划编码
        int life=0;
        int isstat=0;
        if (Excellist != null && Excellist.size() > 0) {
            for (BaseRegionExcel excelData : Excellist) {
                //contains 获取断面名称进行循环数据处理
                String name = excelData.getName();//名称
                String code = excelData.getCode();
                if(name!=null&&!"".equals(name)){
                }else {
                    segment=1;
                }
                if(code!=null&&!"".equals(code)){
                }else {
                    codes=1;
                }
                String lifeStatus = excelData.getLifeStatus();
                String isStatistics = excelData.getIsStatistics();
                if(lifeStatus!=null&&!"".equals(lifeStatus)){
                    Integer integer = Integer.valueOf(lifeStatus);
                    if(integer>=0&&integer<=1){

                    }else {
                        life=1;
                    }
                }
                if(isStatistics!=null&&!"".equals(isStatistics)){
                    Integer integer = Integer.valueOf(isStatistics);
                    if(integer>=0&&integer<=1){

                    }else {
                        isstat=1;
                    }
                }
            }
        }
        if(segment==1){
            maplist.put("msg", "请检查一下模板是否相同，区划名称字段不能为空");
            maplist.put("code", 200);
            maplist.put("data", "");
        }else if(codes==1){
            maplist.put("msg", "请检查一下模板是否相同，区划编码字段不能为空");
            maplist.put("code", 200);
            maplist.put("data", "");
        }else if(life==1){
            maplist.put("msg", "请检查一下模板是否相同，使用状态不能为空请按照对应规则填写");
            maplist.put("code", 200);
            maplist.put("data", "");
        }else if(isstat==1){
            maplist.put("msg", "请检查一下模板是否相同，是否参与计算不能为空请按照对应规则填写");
            maplist.put("code", 200);
            maplist.put("data", "");
        }

        else {
            if (Excellist != null && Excellist.size() > 0) {
                int i=0;
                for (BaseRegionExcel excelData : Excellist) {
                    String code = excelData.getCode();//区划编码
                    String name = excelData.getName();//区划名称
                    //上级区划编码
                    String latitude = excelData.getLatitude();//经度
                    String longitude = excelData.getLongitude();//维度
                    //行政区级别代码
                    String lifeStatus = excelData.getLifeStatus();//使用状态(1-在用0-不用)
                    String ordernum = excelData.getOrdernum();//排序字段
                    String isStatistics = excelData.getIsStatistics();//是否参与计算(0-不参与1-参与)
                    BaseRegion PubCodeRegion=new BaseRegion();
                    if(code!=null&&!"".equals(code)){
                        PubCodeRegion.setCode(code);
                    }
                    if(name!=null&&!"".equals(name)){
                        PubCodeRegion.setName(name);
                    }
                    if(latitude!=null&&!"".equals(latitude)){
                        PubCodeRegion.setLatitude(latitude);
                    }
                    if(longitude!=null&&!"".equals(longitude)){
                        PubCodeRegion.setLongitude(longitude);
                    }
                    if(lifeStatus!=null&&!"".equals(lifeStatus)){
                        PubCodeRegion.setLifeStatus(Integer.valueOf(lifeStatus));
                    }
                    if(ordernum!=null&&!"".equals(ordernum)){
                        PubCodeRegion.setOrdernum(Integer.valueOf(ordernum));
                    }
                    if(isStatistics!=null&&!"".equals(isStatistics)){
                        PubCodeRegion.setIsStatistics(isStatistics);
                    }
                    BaseRegion pubCodeRegion = baseRegionMapper.selectPubCodeRegionByCode(code);
                    if(pubCodeRegion!=null&&!"".equals(pubCodeRegion)){

                    }else {
                        baseRegionMapper.insertPubCodeRegion(PubCodeRegion);
                        i++;
                    }

                }
                if(i>0){
                    maplist.put("msg", "导入成功");
                    maplist.put("code", 200);
                    maplist.put("data", "");
                }else {
                    maplist.put("msg", "导入数据已经存在");
                    maplist.put("code", 200);
                    maplist.put("data", "");
                }
            }else {
                maplist.put("msg", "请使用模板格式导入数据从新导入");
                maplist.put("code", 200);
                maplist.put("data", "");
            }
        }




        return maplist;
    }

    /**
     * 获取子节点列表
     * @param ParentCode
     * @return
     */
    public List<RegionData> getChildrenList(String ParentCode){
        List<RegionData> dataList =new ArrayList<>();
        BaseRegion region=new BaseRegion();
        region.setParentCode(ParentCode);
//        region.setLevelCode(LevelCode);
        List<BaseRegion> list= baseRegionMapper.selectPubCodeRegionList(region);
        for(BaseRegion pubCodeRegion1:list){
            RegionData data =new RegionData();
            data.setLabel(pubCodeRegion1.getName());
            data.setValue(pubCodeRegion1.getCode());
            data.setParentId(pubCodeRegion1.getParentCode());
            data.setOrderNum(pubCodeRegion1.getOrdernum());
            data.setChildren(getChildrenList(pubCodeRegion1.getCode()));
            dataList.add(data);
        }
        return dataList;
    }

    public List<BaseRegion> getRegionListNew(String ParentCode){
        List<BaseRegion> lisst=new ArrayList<>();
        BaseRegion region=new BaseRegion();
        if(ParentCode!=null&&!"".equals(ParentCode)){
            region.setParentCode(ParentCode);
            List<BaseRegion> list= baseRegionMapper.selectPubCodeRegionList(region);
            if(list!=null&&list.size()>0){
                for(BaseRegion pubCodeRegion1:list){
                    lisst.add(pubCodeRegion1);
                    if(pubCodeRegion1!=null&&pubCodeRegion1.getCode()!=null&&!"".equals(pubCodeRegion1.getCode())){
                        List<BaseRegion> regionListNew = getRegionListNew(pubCodeRegion1.getCode());
                        if(regionListNew!=null&&regionListNew.size()>0){
                            lisst.addAll(regionListNew);
                        }
                    }

                }
            }
        }


        return lisst;
    }

    public List<BaseRegion> getChildrenListNew(String ParentCode){
        BaseRegion region=new BaseRegion();
        region.setParentCode(ParentCode);
        List<BaseRegion> list= baseRegionMapper.selectPubCodeRegionList(region);
        for(BaseRegion pubCodeRegion1:list){
            pubCodeRegion1.setChildren(getChildrenListNew(pubCodeRegion1.getCode()));
        }
        return list;
    }

    /**
     * 新增行政区划
     *
     * @param pubCodeRegion 行政区划
     * @return 结果
     */
    @Override
    public int insertPubCodeRegion(BaseRegion pubCodeRegion)
    {
        return baseRegionMapper.insertPubCodeRegion(pubCodeRegion);
    }

    /**
     * 修改行政区划
     *
     * @param pubCodeRegion 行政区划
     * @return 结果
     */
    @Override
    public int updatePubCodeRegion(BaseRegion pubCodeRegion)
    {
        return baseRegionMapper.updatePubCodeRegion(pubCodeRegion);
    }

    /**
     * 批量删除行政区划
     *
     * @param Codes 需要删除的行政区划主键
     * @return 结果
     */
    @Override
    public int deletePubCodeRegionByCodes(String[] Codes)
    {
        return baseRegionMapper.deletePubCodeRegionByCodes(Codes);
    }

    /**
     * 删除行政区划信息
     *
     * @param Code 行政区划主键
     * @return 结果
     */
    @Override
    public int deletePubCodeRegionByCode(String Code)
    {
        return baseRegionMapper.deletePubCodeRegionByCode(Code);
    }

}
